package org.gruposp2p.dnie.cliente.rest;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import com.sun.jersey.core.util.MultivaluedMapImpl;
import dniegp2pclient.DNIeGP2PClientApp;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.gruposp2p.dnie.model.DNIeDocumentToSign;
import org.gruposp2p.dnie.ui.dialogs.ErrorDialog;
import org.gruposp2p.dnie.xml.jaxb.ObjectFactory;

/**
 *
 * @author jj
 *
 *
 */
public class RestFacade {
//TODO mirar
//    Para enviar a un recurso del tipo:
//     @POST
//    public MyBean createBean(List<ObjOne> objList) {}
//    La petición cliente debería ser del estilo:
//    List<ObjOne> objList= new ArrayList<ObjOne>(); 
//    MyBean myBean = this.webResource.path("one/two").type(MediaType.APPLICATION_JSON)
//    .post(MyBean.class, new GenericEntity<List<ObjOne>>(objList){});

    private static Logger logger = LoggerFactory.getLogger(RestFacade.class);

    public static final String SIGNED_DOCUMENTS_RESOURCE_URL =
            "/rest/dnieSignedDocuments";

    public static String remoteHost;

    public RestFacade () {}

    public static ClientResponse postSignedDocument (String xmlSignedDocument) {
        WebResource webResource = null;
        ClientResponse clientResponse = null;
        DefaultClientConfig cc = new DefaultClientConfig();
        cc.getClasses().add(ObjectFactory.class);
        String postURL = System.getProperty("postURL");
        if (postURL == null || "".equals(postURL.trim())) {
            postURL = remoteHost + SIGNED_DOCUMENTS_RESOURCE_URL;
        }
        logger.debug("postURL: " + postURL);
        try {
            webResource = Client.create().resource(postURL);
            MultivaluedMap formData = new MultivaluedMapImpl();
            formData.add("xmlStrSignedDocument", xmlSignedDocument);
            clientResponse = webResource.type(
                    MediaType.APPLICATION_FORM_URLENCODED).post(
                    ClientResponse.class, formData);
            //clientResponse = webResource.type(MediaType.TEXT_PLAIN)
            //        .accept(MediaType.TEXT_PLAIN).post(
            //        ClientResponse.class, xmlSignedDocument);
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            ErrorDialog errorDialog = new ErrorDialog(
                DNIeGP2PClientApp.getApplication().getView().getFrame(), true);
            errorDialog.setErrorMessage( "Error posting to: " + postURL + "\n" +
                    ex.getMessage());
        }
        return clientResponse;
    }

    public static DNIeDocumentToSign getDocumentToSign (String resourceUrl) {
        WebResource webResource;
        DefaultClientConfig cc = new DefaultClientConfig();
        cc.getClasses().add(ObjectFactory.class);
        Client client = Client.create(cc);
        webResource = client.resource(resourceUrl);
        int port = 80;
        if (webResource.getURI().getPort() != -1) {
            port = webResource.getURI().getPort();
        }
        String path = webResource.getURI().getPath();
        int restIndex = path.indexOf("/rest");
        remoteHost = "http://" + webResource.getURI().getHost() + ":" 
                + port + path.substring(0, restIndex);
        logger.debug("remoteHost: " + remoteHost);
        DNIeDocumentToSign document = webResource.accept(
                MediaType.APPLICATION_XML).get(DNIeDocumentToSign.class);
        return document;
    }

}